import Vue from 'vue';
import Vuex from 'vuex';
import _ from 'lodash';

import { Loading } from 'element-ui';
let loading;
function openLoading() {
  loading = Loading.service({
    lock: true,
    background: 'rgba(255,255,255,0.6)',
  });
}
function closeLoading() {
  loading.close();
}

Vue.use(Vuex);
import molle from './molle.js';
import molle2 from './molle2.js';

export default new Vuex.Store({
  modules: {
    molle, //测试模块1
    molle2, //测试模块2
  },
  state: {
    TOKEN: null,
    msg: { name: 'a123' },
  },
  getters: {
    getValue: (state) => (key) => {
      return state[key];
    },
    getTOKEN: (state) => {
      if (state.TOKEN === null) {
        state.TOKEN = localStorage.getItem('TOKEN') || null;
      }
      return state.TOKEN;
    },
    optsFindByPredicate: (state) => {
      return (tarKey, predicate) => {
        let tar = state[tarKey];
        let list = tar.map((v, i) => {
          return _.get(v, 'item');
        });
        let idx = _.findIndex(list, predicate);
        if (idx >= 0) {
          return tar[idx].value;
        } else {
          return null;
        }
      };
    },
    optsFindByValue: (state) => {
      return (tarKey, value) => {
        let tar = state[tarKey];
        let item = _.find(tar, { value: value });
        return _.get(item, 'item');
      };
    },
  },
  mutations: {
    setValue: (state, obj) => {
      state[obj.key] = obj.value;
    },
    setLocal: (state, value) => {
      state.key = value;
      localStorage.setItem('key', value);
    },
    setOpts: (state, { arr, tarKey, labelKey, valueKey }) => {
      if (!_.has(state, tarKey) || !_.isArray(state[tarKey])) return;
      let tar = state[tarKey];
      tar.splice(0, tar.length);
      arr.forEach((v, i) => {
        let obj = {
          label: _.get(v, labelKey),
          value: _.get(v, valueKey),
          item: v,
        };
        tar.push(obj);
      });
    },
  },
  actions: {
    // getOptsFromwhere({ commit }) {
    //   openLoading();
    //   return api
    //     .获取fromwhere关系表()
    //     .then((res) => {
    //       if (res.code == 200 && res.data) return res.data;
    //     })
    //     .then((res) => {
    //       commit('setOpts', {
    //         arr: res,
    //         tarKey: 'optsFromwhere',
    //         labelKey: 'channelName',
    //         valueKey: 'channelFromwhereId',
    //       });
    //     })
    //     .catch((err) => {
    //       console.error(err);
    //     })
    //     .finally((_) => {
    //       closeLoading();
    //     });
    // },
  },
});
